package com.hzb.erp.wechat.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hzb.erp.wechat.entity.WxMenuEntity;
import org.springframework.beans.BeanUtils;

import java.util.LinkedList;
import java.util.List;

/**
* 微信菜单数据转换工具
* */
public class WxMenuUtils {

    /**
    * 扁平化树形结果，并维护id和pid
    * */
    public static List<WxMenuEntity> menuListFlat(List<WxMenuEntity> menuList) {
        List<WxMenuEntity> result = new LinkedList<>();
        long id = 1L;
        if(CollectionUtils.isNotEmpty(menuList)) {
            for (WxMenuEntity main : menuList) {
                WxMenuEntity menu = new WxMenuEntity();
                main.setId(id);
                BeanUtils.copyProperties(main, menu);
                menu.setPid(0L);
                menu.setChildren(null);
                result.add(menu);
                id++;
                if(CollectionUtils.isNotEmpty(main.getChildren())) {
                    for (WxMenuEntity sub : main.getChildren()) {
                        WxMenuEntity menu1 = new WxMenuEntity();
                        BeanUtils.copyProperties(sub, menu1);
                        menu1.setId(id);
                        menu1.setPid(main.getId());
                        result.add(menu1);

                        id++;
                    }
                }
            }
        }
        return result;
    }

    /**
     * 转换数据库里的数据为树形结构
     * 自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
     * 一级菜单最多4个汉字，二级菜单最多8个汉字，多出来的部分将会以“...”代替。
     */
    public static List<WxMenuEntity> buildMenuTree(List<WxMenuEntity> menuList) {
        List<WxMenuEntity> result = new LinkedList<>();
        if(CollectionUtils.isNotEmpty(menuList)) {
            for (WxMenuEntity item : menuList) {
                if (item.getPid() == 0L) {
                    item.setChildren(new LinkedList<>());
                    result.add(item);
                }
            }
        }

        if(CollectionUtils.isNotEmpty(result)) {
            for (WxMenuEntity item1 : result) {
                for (WxMenuEntity item2 : menuList) {
                    if (item1.getId().equals(item2.getPid())) {
                       item1.getChildren().add(item2);
                    }
                }
                if(CollectionUtils.isEmpty(item1.getChildren()) || item1.getChildren().size()<5) {
                    item1.getChildren().add(newBtn());
                }
            }
        }
        if (CollectionUtils.isEmpty(result) || result.size()<3) {
            result.add(newBtn());
        }
        return result;

    }

    private static WxMenuEntity newBtn() {
        WxMenuEntity addBtn = new WxMenuEntity();
        addBtn.setType("add");
        addBtn.setName("+");
        return addBtn;
    }

}
